


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>校园论坛管理系统</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" href="../layui/css/layui.css" media="all">
  <link rel="stylesheet" href="../layui/css/admin.css" media="all">
  <link rel="stylesheet" href="../CSS/login.css" media="all">

  <style>
    #canvas {
        display: inline-block;
        border: 1px solid #ccc;
        border-radius: 5px;
        cursor: pointer;
    }
  </style>
</head>
<body>

  <div class="layadmin-user-login layadmin-user-display-show" id="LAY-user-login" style="display: none;">

    <div class="layadmin-user-login-main">
      <div class="layadmin-user-login-box layadmin-user-login-header">
        <h2>校园论坛管理系统</h2>
        <p>Campus Forum Management System</p>
      </div>
      <div class="layadmin-user-login-box layadmin-user-login-body layui-form">
        <div class="layui-form-item">
          <label class="layadmin-user-login-icon layui-icon layui-icon-username" for="LAY-user-login-username"></label>
          <input type="text" name="userId" id="LAY-user-login-userId" lay-verify="required" placeholder="账号" class="layui-input">
        </div>
        <div class="layui-form-item">
          <label class="layadmin-user-login-icon layui-icon layui-icon-password" for="LAY-user-login-password"></label>
          <input type="password" name="password" id="LAY-user-login-password" lay-verify="required" placeholder="密码" class="layui-input">
        </div>
        <div class="layui-form-item">
          <div class="layui-row">
            <div class="layui-col-xs7">
              <label class="layadmin-user-login-icon layui-icon layui-icon-vercode" for="LAY-user-login-vercode"></label>
              <input type="text" name="vercode" id="LAY-user-login-vercode" lay-verify="required" placeholder="图形验证码" class="layui-input">
            </div>
            <div class="layui-col-xs5">
              <div style="margin-left: 10px;">
                <canvas id="canvas" width="100" height="36"></canvas>
              </div>
            </div>
          </div>
        </div>
        <div class="layui-form-item" style="margin-bottom: 20px;">
          <input type="checkbox" name="remember" lay-skin="primary" title="记住密码" id="remember">
          <!-- <a href="./login/forget.html" class="layadmin-user-jump-change layadmin-link" style="margin-top: 7px;">忘记密码？</a> -->
        </div>
        <div class="layui-form-item">
          <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="LAY-user-login-submit">登 入</button>
        </div>
        <!-- <div class="layui-trans layui-form-item layadmin-user-login-other">
          <label>社交账号登入</label>
          <a href="javascript:;"><i class="layui-icon layui-icon-login-qq"></i></a>
          <a href="javascript:;"><i class="layui-icon layui-icon-login-wechat"></i></a>
          <a href="javascript:;"><i class="layui-icon layui-icon-login-weibo"></i></a>
          
          <a href="./login/reg.html" class="layadmin-user-jump-change layadmin-link">注册帐号</a>
        </div> -->
      </div>
    </div>
    
    <div class="layui-trans layadmin-user-login-footer">
      
      <p>© 2018 <a href="https://www.layui1.com/" target="_blank">layui1.com</a></p>
      <p>
        <span><a href="https://www.layui1.com/" target="_blank">前往官网</a></span>
      </p>
    </div>
    
    <!--<div class="ladmin-user-login-theme">
      <script type="text/html" template>
        <ul>
          <li data-theme=""><img src="{{ layui.setter.base }}style/res/bg-none.jpg"></li>
          <li data-theme="#03152A" style="background-color: #03152A;"></li>
          <li data-theme="#2E241B" style="background-color: #2E241B;"></li>
          <li data-theme="#50314F" style="background-color: #50314F;"></li>
          <li data-theme="#344058" style="background-color: #344058;"></li>
          <li data-theme="#20222A" style="background-color: #20222A;"></li>
        </ul>
      </script>
    </div>-->
    
  </div>
  <script src="./layui/layui.all.js"></script> 
  <script src="./layui/lay/modules/captcha.js"></script> 
  <script>
  layui.use(['jquery','form','captcha'], function(){
    var $ = layui.$
    var form = layui.form
    var capcha = layui.captcha

form.render();

    var show_num = [];
    capcha.draw(show_num);
    //显示验证码
    $("#canvas").on('click',function(){
      capcha.draw(show_num);
    });
  
    
     // 初始化记住密码功能
  function initRememberMe() {
    // 尝试读取本地存储
    const savedData = localStorage.getItem('userCredential');
    // console.log(savedData);
    
    if (savedData) {
      try {
        // Base64 解码（简单防护）
        const decoded = JSON.parse(atob(savedData));
        // console.log(decoded);
        
        $('#LAY-user-login-userId').val(decoded.userId);
        $('#LAY-user-login-password').val(decoded.password);
        $('#remember').prop('checked', true);
        form.render('checkbox'); // 更新复选框样式
      } catch(e) {
        localStorage.removeItem('userCredential');
      }
    }
  }
  // 初始化执行
  initRememberMe();

   

     // 提交登录
  // $('button[lay-filter="LAY-user-login-submit"]').click( function(){
   form.on('submit(LAY-user-login-submit)', function(data){
    var num = show_num.join("");
      var code = data.field["vercode"];
      console.log(num)
      //验证码判断
      if(code != num){
        layer.msg('验证码错误,请重新输入', {
        offset: '15px'
       ,icon: 5
       });
       return
      }

    var loading = layer.load(2); // 显示加载状态
    // 构造请求数据
    var postData = {
      userId: $('#LAY-user-login-userId').val(),
      password: $('#LAY-user-login-password').val(),
      // vercode: obj.field.vercode
    };
    console.log(postData);
    // 如果勾选记住密码
    if (data.field.remember) {
    
    // Base64 编码存储
      localStorage.setItem('userCredential', btoa(JSON.stringify(postData)));

}else{
  // 取消记住时清除存储
      localStorage.removeItem('userCredential');
}
    // 发送登录请求
    $.ajax({
      url: '/login',
      type: 'POST',
      contentType: 'application/json',
      data: JSON.stringify(postData),
      success: function(res) {
        // console.log(res);
        
        layer.close(loading);
        if(res.code === 0) {
          // 1. 提取 Payload 部分
const token = res.data; // 去掉 Bearer 前缀
const payloadBase64 = token.split('.')[1]; // 获取中间段

// 2. Base64 解码
// 注意：需要处理 URL安全的Base64（将 '-' 替换 '+'，'_' 替换 '/'）
const decodedPayload = decodeURIComponent(
  atob(payloadBase64.replace(/-/g, '+').replace(/_/g, '/'))
  .split('')
  .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
  .join('')
);

// 3. 解析为 JSON
const payload = JSON.parse(decodedPayload);
// console.log(payload);


          layer.msg('登录成功', {icon: 1});
          localStorage.setItem('token',res.data);
          localStorage.setItem('username',payload.username)
          localStorage.setItem('avatar',payload.avatar)
          localStorage.setItem('userId',payload.userId)
          setTimeout(function(){
            location.href = '../index.html'; // 跳转首页
          }, 1500);
        } else {
          layer.msg(res.msg || '登录失败', {icon: 2});
          // refreshCaptcha(); // 刷新验证码
        }
      },
      error: function(xhr) {
        layer.close(loading);
        layer.msg('请求失败: ' + xhr.statusText, {icon: 2});
        // refreshCaptcha();
      }
    });
    return false; // 阻止默认提交
  });
    
    
    
    
  });
  </script>
</body>
</html>